<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { scmGoodsData } from '#/views/backend/scmGoods/config';

import { defineEmits, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button, Input, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getAttachmentList } from '#/api/goods/scmGoods';

// 定义要发送的事件
type EmitEvents = {
  pushData: [data: scmGoodsData[]];
};
const emit = defineEmits<EmitEvents>();

const [Modal, modalApi] = useVbenModal({
  class: 'w-3/6',
  footer:false,
  onCancel() {
    modalApi.close();
  },
  onConfirm() {},
});

const gridOptions: VxeTableGridOptions<scmGoodsData> = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  columns: [
    {
      type: 'checkbox', // 多选列（自带全选框）
      width: 70, // 列宽
      align: 'center', // 居中
      fixed: 'left', // 固定在最左侧
      title: '', // 表头文字
    },
    { field: 'id', title: 'ID', width: 80 },
    { field: 'topic', title: '细目', width: 60 },
    { field: 'full_url', title: '预览', width: 120, cellRender: { name: 'CellImage' } },
    { field: 'mimetype', title: '类型', width: 120 },
    {
      field: 'size',
      sortable: true,
      title: '大小',
      width: 80,
      slots: { default: 'size' },
    },
    {
      field: 'createtime',
      sortable: true,
      title: '最后上传时间',
      width: 160,
      slots: { default: 'createtime' },
    },
    {
      field: 'name',
      title: '大小',
      width: 120,
    },
    {
      field: 'action',
      title: '操作',
      width: 100,
      slots: { default: 'action' },
    },
  ],
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        // 2. 调接口
        const res = await getAttachmentList({
          page: page.currentPage,
          limit: page.pageSize,
          order: 'lastuploadtime,desc',
          quick_search: quick_search.value,
        });

        return { items: res.list, total: res.total };
      },
    },
    sort: true,
  },
  toolbarConfig: {
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

/**
 *  快速查询查询
 */
const quick_search = ref();
function doSearch() {
  gridApi.query();
}

/**
 * 格式化时间戳
 */
function formatTimestamp(timestampStr: string): string {
  if (!timestampStr) {
    return '-';
  }

  try {
    // 解析时间戳，确保是数字
    let timestamp = Number(timestampStr);

    // 如果时间戳位数较少（秒级别），转换为毫秒级别
    if (timestamp.toString().length < 13) {
      timestamp = timestamp * 1000;
    }
    const date = new Date(timestamp);
    // 格式化日期为 YYYY-MM-DD HH:mm:ss 格式
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch {
    return '-';
  }
}

/**
 * 格式化文件大小
 */
function formatFileSize(sizeStr: string): string {
  const size = Number.parseFloat(sizeStr);
  if (size <= 0) {
    return '0 B';
  }

  try {
    const i = Math.floor(Math.log(size) / Math.log(1024));
    return `${Number.parseInt((size / 1024 ** i).toFixed(i < 2 ? 0 : 2)) * 1} ${['B', 'KB', 'MB', 'GB', 'TB'][i]}`;
  } catch {
    return '-';
  }
}

/**
 * 处理推送按钮点击事件
 */
function handlePush(row: scmGoodsData) {
  // 发送数据到父组件，确保总是数组格式
  emit('pushData', [row]);
  // 关闭模态框
  modalApi.close();
}

/**
 * 处理工具栏选择按钮点击事件
 */
function handleToolbarSelect() {
  // 获取选中的所有行数据
  const selectedRecords = gridApi.grid.getCheckboxRecords();

  if (selectedRecords && selectedRecords.length > 0) {
    // 发送选中的数据到父组件
    emit('pushData', selectedRecords);
    // 关闭模态框
    modalApi.close();
  }
}
</script>

<template>
  <Modal title="选择文件">
    <div class="w-full">
      <Grid style="width: 100%">
        <template #toolbar-actions>
          <Button type="primary" @click="handleToolbarSelect">选择</Button>
        </template>
        <template #toolbar-tools>
          <Input v-model:value="quick_search" allow-clear placeholder="通过原始名模糊搜索" style="width: 200px; margin-right: 8px" @change="doSearch" />
        </template>
        <!-- 大小列插槽，处理可能的 NaN 和 undefined -->
        <template #size="{ row }">
          <template v-if="row.size > 0 && !isNaN(parseFloat(row.size))">
            {{ formatFileSize(row.size) }}
          </template>
          <template v-else>-</template>
        </template>

        <!-- 最后上传时间插槽，处理时间戳转换 -->
        <template #createtime="{ row }">
          <template v-if="row.createtime">
            {{ formatTimestamp(row.createtime) }}
          </template>
          <template v-else>-</template>
        </template>

        <!-- 操作列插槽 -->
        <template #action="{ row }">
          <Space>
            <Button type="primary"  class="my-green-btn" size="small" @click="handlePush(row)">选择</Button>
          </Space>
        </template>
      </Grid>
    </div>
  </Modal>
</template>
<style lang="scss" scoped></style>
